App.controller('taskController', ['$scope', '$state', '$stateParams', 'Page', 'Form', function($scope, $state, $stateParams, Page, Form) {

	$scope.process = {};
    $scope.task = $stateParams.task;
    $scope.properties = [];
    $scope._properties = {};
    $scope.selectAssignee = false;
    $scope.print = false;
    $scope.$watch('properties', function (newValue, oldValue) {
        if (newValue && newValue.length > 0) {
            $scope._properties = {};
            $(newValue).each(function(index, property) {
                $scope._properties[property.id] = property;
            });
        }
    });

    $scope.cancel = function() {// 返回
    	 window.history.back();
    };

    if ($scope.task) {
        $scope.task.form = $scope.task.form || {};     
        $scope.processInstanceId = $scope.task.processInstanceId;
        // 获取表单
        Page.ajaxGet('bpm/task/' + $scope.task.id + '/form.do', null, function(resp) {
        	$scope.process = resp.data.processDefinition;
        	$scope.processPath = 'views/bpm/diagram-viewer/index.html?processDefinitionId=' + $scope.process.id + '&processInstanceId=' + $scope.task.processInstanceId;
            $scope.properties = resp.data.properties || [];
            $scope.task.form = resp.data.form || {};
            $scope.comments = resp.data.comments || [];
            $scope.key = resp.data.key;
            $scope.buttons = resp.data.buttons || [];
        });

        // 按钮事件
        $scope.approval = function(button) {
        	if (!$scope.selectAssignee){
        		$scope.assigneeElements = [];
            	if($scope.properties && $scope.properties.length > 0){
            		$($scope.properties).each(function(index, property) {
            			if((property.type.name === 'userSelect' || property.type.name === 'userMultiSelect') 
            					&& property.id.indexOf(button.id) != -1 ){
            				$scope.assigneeElements[$scope.assigneeElements.length] = {
            					id: property.id,
            					name: property.name,
            					type: property.type.name,
            					value: ''
            				};
            			}
            		});
            	}
        	}
        	
        	if(!$scope.selectAssignee && $scope.assigneeElements.length > 0){
        		$scope.selectAssignee = true ;
        		$scope.currentButton = button;
        	}else {
        		var formData = $scope.task.form;
            	var formData2 = Form.toJson('#properties-form');
            	for(var key in formData2) {
                    if(formData[key] == undefined) {
                    	formData[key] = formData2[key];
                    }
                }
            	
            	var data = {};
            	for (var key in formData ) {
            		var temp = $scope._properties[key];
            		if(temp != undefined && temp.readable === true && temp.writable === true) {
            			data[key] = formData[key];
            		}else{
            			data[key] = formData[key];
            		}
            	}
            	
                if($scope.selectAssignee){
                	var assigneeFlag = false;
                	$($scope.assigneeElements).each(function(index, element) {
                		data[element.id] = element.value;
            			if(element.value != ''){
            				assigneeFlag = true;
            			}
            		});
                	if(!assigneeFlag){
                		 Page.alert("请选择办理人!");
                         return;
                	}
                }
                
                // 默认流程条件
                var conditions = button.conditions;
                for(var key in conditions) {
                    if (typeof data[key] == 'undefined' || data[key].length == 0) {
                    	data[key] = conditions[key];
                    } else if (data[key] != conditions[key]) {
                        Page.alert("页面取值与流程变量不一致！");
                        return;
                    }
                }
                data.outcome = button.name || button.id;
            	
                Page.ajaxPost('bpm/task/'+$scope.task.id+'/complete.do', {properties: data}, function(resp) {
                    Page.alert("提交成功", function() {
                        window.history.back();
                    });
                });
            }
        }
        
        //退回按钮
        $scope.toBack = function() {
        	Page.ajaxPost('bpm/task/backActs/'+$scope.task.id+'.do',{}, function(resp) {
        		$scope.actList = resp.data;
        		if($scope.actList != undefined && $scope.actList.length > 0) {
            		$scope.toBackModal.show();
            	} else {
            		Page.notice("该任务不能退回!");
            	}
            });
        	
        }
        $scope.selectCancel = function(){
        	$scope.selectAssignee = false;
        }

    }else {
        window.history.back();
        return;
    }
    
    $scope.bakPrint = function(){
    	if($scope.task.processInstanceId){
    		var dataSourceUrl = 'bpm/process/' + $scope.task.processInstanceId + '/print.do';
            window.open("views/official/printWithTemplate.jsp?dataSourceUrl=" + dataSourceUrl ,"_blank");
    	}else{
    		Page.alert("参数错误!");
    	}
    };
    
    $scope.processTrackGrid = {
        	options: {
	            scroller: true,
	            paging: false   
            }
    };

    $scope.clickBackAct = function(activityId) {
        $scope.activityId = activityId;
    }
    
    $scope.toBackModal = {
    	onOkClick : function(){
	    	$scope.clickTrue = true;
	    	//进行退回
	    	if($scope.activityId && $scope.activityId != ''){
	    		Page.ajaxPost('bpm/task/toBackTask.do', {actId: $scope.activityId,taskId : $scope.task.id}, function(resp) {
	                Page.alert("退回成功!", function() {
	                    window.history.back();
	                });
	            });
	    	}
    	},
    	onHidden : function(){
    		if(!$scope.clickTrue) {
            	$scope.activityId = "";
    		}
    	}
    }

}]);

App.directive('edBpmInput', ['$parse', '$compile', function ($parse, $compile) {
    return {

        restrict: 'A',

        controller: function($scope, $element, $rootScope){
        },

        link: function (scope, elem, attrs) {

            var model = attrs.ngModel;
            var index = model.lastIndexOf('.');
            model = model.substring(index + 1, model.length);
            // 添加name属性
            $(elem).attr("name", model);

            scope.$watch('_properties', function (newValue, oldValue) {
                if (newValue) {
                    var prop = newValue[model];
                    if (prop) {
                    	//规定:可读并且必须时才是readonly
                        if (prop.readable === true && prop.required ===true) {
                            $(elem).attr("readonly","readonly");
                            return;
                        }
                    }
                }
            });
        }
    };
}]);
